package com.hspedu.newData.dmsxl.树.搜索树;

import com.hspedu.newData.dmsxl.ds.TreeNode;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yh
 * @description: 
 * @CreateTime: 2025-05-06 
 * @Version: 1.0
 */

public class LC530二叉搜索树的最小绝对差 {

    public int getMinimumDifference(TreeNode root) {

        int minimumDifference = getMinimumDifference(root, 0,100000);
        return minimumDifference;
    }

    public int getMinimumDifference(TreeNode root,int difference,int res){
        if (root == null) return res;

        int differenceLeft = 100000;
        int differenceRight = 100000;
        if (root.left != null){
            differenceLeft = getMinimumDifference(root.left,root.val - root.left.val,res);
        }
        if (root.right != null){
            differenceRight = getMinimumDifference(root.right,root.right.val - root.val,res);
        }
        res = Math.min(res,Math.min(differenceLeft,differenceRight));
        return res;
    }


    // todo 效率很低
    public int getMinimumDifference1(TreeNode root) {

        inorderTraversal(root);

        int min = Integer.MAX_VALUE;
        for (int i = 1; i < list.size(); i++) {
            if ((list.get(i) - list.get(i-1)) < min){
                min = list.get(i) - list.get(i-1);
            }
        }
        return min;
    }

    private List<Integer> list = new ArrayList<>();

    public void inorderTraversal(TreeNode root){
        if (root == null){
            return;
        }

        inorderTraversal(root.left);
        list.add(root.val);
        inorderTraversal(root.right);
    }




}
